import java.io.*;
import java.util.HashSet;

/**
 * @author lht
 * @version 1.0
 * @description: TODO
 * @date 2024/11/12 17:40
 */


public class HashSetSerializationExample {
    public static void main(String[] args) {
        // 创建一个 HashSet 并添加一些元素
        HashSet<String> hashSet = new HashSet<>();
        hashSet.add("Apple");
        hashSet.add("Banana");
        hashSet.add("Cherry");

        // 序列化 HashSet 对象
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("hashset.ser"))) {
            out.writeObject(hashSet);
            System.out.println("HashSet 已序列化");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 反序列化 HashSet 对象
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("hashset.ser"))) {
            HashSet<String> deserializedHashSet = (HashSet<String>) in.readObject();
            System.out.println("HashSet 已反序列化");
            System.out.println("反序列化的 HashSet: " + deserializedHashSet);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
